from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from model.user import Schedule
from schema.schedule import IScheduleCreate, ISchedulePut


class CRUDTask:
    async def get(self, task_id: int, db_session: AsyncSession):
        return (await db_session.execute(
            select(Schedule)
            .where(Schedule.id_task == task_id)
            .options(selectinload(Schedule.sub_task), selectinload(Schedule.address)))).scalars().all()

    async def create_schedule(self, schema: IScheduleCreate, db_session: AsyncSession):
        db_obj = Schedule(**schema.dict())
        db_session.add(db_obj)
        await db_session.commit()
        await db_session.refresh(db_obj)
        return db_obj

    async def modify_schedule(self, schedule_id: int, schema: ISchedulePut, db_session: AsyncSession):
        args = schema.dict()
        schedule_obj = await db_session.execute(update(Schedule).where(Schedule.id==schedule_id),
                                                args)
        await db_session.commit()
        return 'ok'




task = CRUDTask()
